﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Revit;
using YArchitech.Revit.RevitExtension;

namespace YJKArch.DimensionModule
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdArrowDim : YJKCommandManual
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		protected override Result YJKExcute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			if (CmdArrowDim._hWndRevit == null)
			{
				Process[] processesByName = Process.GetProcessesByName("Revit");
				if (processesByName.Length != 0)
				{
					CmdArrowDim._hWndRevit = new WindowHandle(processesByName[0].MainWindowHandle);
				}
			}
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Autodesk.Revit.DB.Document document = activeUIDocument.Document;
			Autodesk.Revit.DB.View activeView = document.ActiveView;
			DimDate.FontFamily = AssistFunc.GetSystemFontTypeStringArray(document);
			IEnumerable<Element> enumerable = new FilteredElementCollector(document).OfClass(typeof(Autodesk.Revit.DB.ElementType)).ToElements();
			List<string> list = new List<string>();
			foreach (Element element in enumerable)
			{
				Autodesk.Revit.DB.ElementType elementType = (Autodesk.Revit.DB.ElementType)element;
				if (elementType.get_Parameter(BuiltInParameter.ALL_MODEL_FAMILY_NAME).AsString() == "箭头")
				{
					list.Add(elementType.Name);
				}
			}
			if (list.Count == 0)
			{
				message = "当前文档箭头族类型为空";
				return Autodesk.Revit.UI.Result.Failed;
			}
			DimDate.ArrowType = list;
			DlgArrowDim dlgArrowDim = new DlgArrowDim();
			dlgArrowDim.Show(CmdArrowDim._hWndRevit);
			int wMsg = 7;
			CmdArrowDim.SendMessage(CmdArrowDim._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			XYZ xyz = null;
			XYZ xyz2 = null;
			XYZ xyz3 = null;
			ModelCurve modelCurve = null;
			ElementSet elementSet = new ElementSet();
			Result result;
			for (;;)
			{
				Transaction transaction = new Transaction(document);
				transaction.Start("revit");
				try
				{
					xyz = activeUIDocument.Selection.PickPoint("请选择一个点");
					dlgArrowDim.Enabled = false;
					xyz2 = activeUIDocument.Selection.PickPoint("请选择第二个点");
					Line line = YJKLineEx.YJKGetBound(xyz, xyz2);
					Plane plane = RevitVersionFuncs.CreatePlanByNormalAndOrigin(xyz2.CrossProduct(xyz), xyz);
					SketchPlane sketchPlane = RevitVersionFuncs.NewSketchPlane(document, plane);
					modelCurve = document.Create.NewModelCurve(line, sketchPlane);
					transaction.Commit();
				}
				catch (Exception)
				{
					transaction.RollBack();
					if (dlgArrowDim.Enabled)
					{
						dlgArrowDim.Close();
						result = Autodesk.Revit.UI.Result.Succeeded;
						break;
					}
					dlgArrowDim.Enabled = true;
					continue;
				}
				Transaction transaction2 = new Transaction(document);
				try
				{
					transaction2.Start("thridpoint");
					xyz3 = activeUIDocument.Selection.PickPoint("请选择第三个点");
					double x = xyz2.X;
					double x2 = xyz3.X;
					transaction2.Commit();
				}
				catch (Exception)
				{
					transaction2.RollBack();
					if (dlgArrowDim.Enabled)
					{
						dlgArrowDim.Close();
					}
					else
					{
						dlgArrowDim.Enabled = true;
					}
				}
				if (!(dlgArrowDim.alignStyle == "在线端"))
				{
					if (dlgArrowDim.alignStyle == "齐线中")
					{
						if (xyz3 == null)
						{
                            //(xyz + xyz2) / 2.0;
						}
						else
						{
                            //(xyz3 + xyz2) / 2.0;
						}
					}
					else if (dlgArrowDim.alignStyle == "齐线端")
					{
					}
				}
				XYZ xyz4;
				if (xyz3 == null)
				{
					xyz4 = xyz2 - xyz;
					YJKLineEx.YJKGetBound(xyz, xyz2);
				}
				else
				{
					xyz4 = xyz3 - xyz2;
					YJKLineEx.YJKGetBound(xyz2, xyz3);
				}
				Element selectType = Helper.GetSelectType<TextNoteType>(document, dlgArrowDim.fontType);
				byte[] array = null;
				byte[] array2 = null;
				if (dlgArrowDim.LineUpText != null && dlgArrowDim.LineUpText.Length > 0)
				{
					array = Encoding.Default.GetBytes(dlgArrowDim.LineUpmaxLenth);
				}
				double num = Helper.FontSize(selectType as TextNoteType);
				selectType.get_Parameter(BuiltInParameter.TEXT_SIZE).AsDouble();
				int scale = activeView.Scale;
				if (dlgArrowDim.LineDownText != null && dlgArrowDim.LineDownText.Length > 0)
				{
					array2 = Encoding.Default.GetBytes(dlgArrowDim.LineDownmaxLent);
				}
				if (array != null && array.Length != 0)
				{
					int num2 = array.Length;
				}
				if (array2 != null && array2.Length != 0)
				{
					int num3 = array2.Length;
				}
				double num4 = 0.4 * (double)activeView.Scale / 100.0;
				int lineUpRows = dlgArrowDim.lineUpRows;
				double num5 = 0.2 * (double)activeView.Scale / 100.0;
				int lineUpRows2 = dlgArrowDim.lineUpRows;
				Element selectType2 = Helper.GetSelectType<Autodesk.Revit.DB.ElementType>(document, dlgArrowDim.arrowType);
				XYZ baseVec = null;
				XYZ upVec = null;
				if (xyz2 != null)
				{
					new XYZ(xyz2.X, xyz2.Y, xyz2.Z);
					baseVec = new XYZ(1.0, 0.0, 0.0);
					upVec = new XYZ(0.0, 0.0, 1.0);
				}
				Transaction transaction3 = new Transaction(document, "leader");
				transaction3.Start();
				try
				{
					XYZ origin;
					if (xyz3 == null)
					{
						if ((xyz4.X >= 0.0 && xyz4.Y >= 0.0) || (xyz4.X >= 0.0 && xyz4.Y <= 0.0))
						{
							origin = new XYZ(xyz2.X + 0.5 * (double)activeView.Scale / 100.0, xyz2.Y + 0.5 * (double)activeView.Scale / 100.0, xyz2.Z);
						}
						else
						{
							origin = new XYZ(xyz2.X - 0.5 * (double)activeView.Scale / 100.0, xyz2.Y - 0.5 * (double)activeView.Scale / 100.0, xyz2.Z);
						}
					}
					else
					{
						origin = new XYZ(xyz3.X + 0.5 * (double)activeView.Scale / 100.0, xyz3.Y + 0.5 * (double)activeView.Scale / 100.0, xyz3.Z);
					}
                    TextNote textNode = document.GetTextNode(document.ActiveView, origin, baseVec, upVec, 0.0001, (TextAlignFlags)64, (TextNoteLeaderTypes)0, (TextNoteLeaderStyles)1, xyz, xyz2, ".");
					elementSet.Insert(textNode);
					if (xyz3 != null)
					{
						RevitElementExtension.SetTextNoteCoord(textNode, xyz3);
						textNode.HyGetLeaders().get_Item(0).Elbow = xyz2;
					}
					textNode.TextNoteType.get_Parameter(BuiltInParameter.LEADER_ARROWHEAD).Set(selectType2.Id);
					if (array != null)
					{
						RevitElementExtension.SetTextNoteWidth(textNode, (double)array.Length * num);
					}
					else
					{
						RevitElementExtension.SetTextNoteWidth(textNode, 0.0);
					}
					document.Delete(modelCurve.Id);
					if (dlgArrowDim.LineUpText != null && dlgArrowDim.LineUpText.Trim() != "" && dlgArrowDim.alignStyle == "在线端")
					{
						textNode.Text = dlgArrowDim.LineUpText;
					}
					transaction3.Commit();
				}
				catch (Exception)
				{
				}
				Transaction transaction4 = new Transaction(document, "group1");
				transaction4.Start();
				RevitVersionFuncs.NewGroup(document, elementSet);
				transaction4.Commit();
				xyz3 = null;
			}
			return result;
		}

		public static WindowHandle _hWndRevit;
	}
}
